﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace AllTalkProxy
{
    public class Friend
    {
        public List<Jid> Jid {get; private set;}
        public string Name { get; private set; }
        public string Subscription {get; private set;}
        public string Picture { get; private set; }
        public string Status { get; private set; }

        public Friend(XElement friendElement)
        {
            if (this.Jid == null)
                this.Jid = new List<Jid>();
            this.Jid.Add(new Jid(friendElement.Attribute("jid").Value));
            this.Name = friendElement.GetAttribute("name");
            this.Subscription = friendElement.Attribute("subscription").Value;
        }

        public Friend(Jid jidRecieved)
        {
            if (this.Jid == null)
                this.Jid = new List<Jid>();
            this.Jid.Add(jidRecieved);
            this.Name = "";
            this.Picture = "";
            this.Status = "";
           
        }

        public void UpdateFriendPresence(Jid jidRecieved, XElement presenceXml)
        {
            Jid jidToUpdate = this.Jid.Where(j => j.Value == jidRecieved.Value).FirstOrDefault();
            if (jidToUpdate == null)
            {
                jidToUpdate = new Jid(jidRecieved.Value);
                if (this.Jid.Count == 1 && this.Jid[0].Presence == Presence.None)
                {
                    this.Jid.RemoveAt(0);
                }
                this.Jid.Add(jidToUpdate);
            }
            if (presenceXml != null)
            {
                jidToUpdate.UpdatePresence(presenceXml);
            }
        }
   
    }

    public static class XEtensions
    {
        public static string GetAttribute(this XElement element, XName attributeName)
        {
            XAttribute attribute = element.Attribute(attributeName);
            if (attribute != null)
            {
                return attribute.Value;
            }
            return string.Empty;
        }
    }
}
